import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'login',
    component: () => import(/* webpackChunkName: "login" */ '../components/LoginPage.vue')
  },
  // 重定向，
  {
    path: '/',
    redirect:'/login'
  },
  {
    path: '/home',
    name: 'home',
    component: () => import(/* webpackChunkName: "home" */ '../components/HomePage.vue'),
    // 将页面重定向到子页面
    redirect:'/welcome',
    // 配置子路由
    children:[{
      path:'/welcome',
      component:() => import('../components/WelcomeCase.vue')
    },
    {
      path:'/users',
      component:() => import('../components/user/UsersCase.vue')
    },
    {
      path:'/rights',
      component:() => import('../components/power/RightsCase.vue')
    },
    {
      path:'/roles',
      component:() => import('../components/power/RolesCase.vue')
    }]
  },
  
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 挂载路由导航守卫
router.beforeEach((to,from,next) =>{
  // to将要访问的路径
  // from 代表从哪个路径来的
  // next 是一个函数表示放行
  // next() 放行  next("/login") 强制跳转到login页面
  if(to.path === '/login'){
    // 直接放行
    return next();
  }
  // 获取token
  const token = sessionStorage.getItem('token');
  // 如果token不存在,表示没有登录,强制跳转到login页面
  if(!token) {
    return next('/login');
  }
  // 有token直接放行
  next();
})

export default router
